package com.sicpa.web.controller.system;

import com.sicpa.common.annotation.Log;
import com.sicpa.common.constant.DataInPathConstants;
import com.sicpa.common.core.controller.BaseController;
import com.sicpa.common.core.domain.AjaxResult;
import com.sicpa.common.core.domain.entity.AntiCounterfeitingRegisteredOffice;
import com.sicpa.common.core.domain.entity.AssuranceBusinessDataReport;
import com.sicpa.common.core.domain.entity.SysUser;
import com.sicpa.common.core.page.TableDataInfo;
import com.sicpa.common.enums.BusinessType;
import com.sicpa.common.enums.RoleEnum;
import com.sicpa.common.utils.SecurityUtils;
import com.sicpa.common.utils.StringUtils;
import com.sicpa.common.utils.poi.ExcelUtil;
import com.sicpa.system.service.IAntiCounterfeitingRegisteredOfficeService;
import com.sicpa.system.service.IAssuranceBusinessDataReportService;
import com.sicpa.system.service.ICheckUserPowerService;
import com.sicpa.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @program: anti-fake
 * @description: 鉴证业务报告管理
 * @author: wmj
 * @create: 2020-08-31
 * @ClassName: AssuranceBusinessDataReportController
 */
@Api(tags = "鉴证业务报告管理")
@RestController
@RequestMapping("/business/report")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class AssuranceBusinessDataReportController extends BaseController {

    private IAssuranceBusinessDataReportService iAssuranceBusinessDataReportService;

    private ICheckUserPowerService iCheckUserPowerService;

    private IAntiCounterfeitingRegisteredOfficeService iAntiCounterfeitingRegisteredOfficeService;

    private ISysUserService userService;

    @Autowired
    public AssuranceBusinessDataReportController(IAssuranceBusinessDataReportService iAssuranceBusinessDataReportService, ICheckUserPowerService iCheckUserPowerService, IAntiCounterfeitingRegisteredOfficeService iAntiCounterfeitingRegisteredOfficeService,ISysUserService userService) {
        this.iAssuranceBusinessDataReportService = iAssuranceBusinessDataReportService;
        this.iCheckUserPowerService = iCheckUserPowerService;
        this.iAntiCounterfeitingRegisteredOfficeService = iAntiCounterfeitingRegisteredOfficeService;
        this.userService = userService;
    }

    /**
     * 事务所录入鉴证业务报告
     */
    @Log(title = "普通事务所录入鉴证业务报告", businessType = BusinessType.INSERT)
    @ApiOperation("普通事务所录入鉴证业务报告")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody AssuranceBusinessDataReport assuranceBusinessDataReport) {
        assuranceBusinessDataReport.setDataUploadPath(DataInPathConstants.OFFICE_INPUT);

        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = user.getIsOfficeAccount();

        if (1 == isOfficeAccount) {
            AntiCounterfeitingRegisteredOffice offices = iAssuranceBusinessDataReportService.getOfficeByNum();
            if (offices != null) {
                return iAssuranceBusinessDataReportService.insertReport(assuranceBusinessDataReport);
            } else {
                return AjaxResult.error("该事务所账号错误");
            }
        } else {
            return AjaxResult.error("该事务所账号错误");
        }

    }

    /**
     * 需审核事务所录入
     *
     * @param assuranceBusinessDataReport
     * @return
     */
    @Log(title = "需审核事务所录入", businessType = BusinessType.INSERT)
    @ApiOperation("需审核事务所录入")
    @PostMapping("/approveAdd")
    @PreAuthorize("@ss.hasPermi('assurance:need:review')")
    public AjaxResult approveAdd(@Validated @RequestBody AssuranceBusinessDataReport assuranceBusinessDataReport) {
        AntiCounterfeitingRegisteredOffice offices = iAssuranceBusinessDataReportService.getOfficeByNum();
        if (offices != null) {
            assuranceBusinessDataReport.setContrastStatus("0");
            assuranceBusinessDataReport.setDataUploadPath(DataInPathConstants.OFFICE_INPUT);
        }
        return iAssuranceBusinessDataReportService.insertReport(assuranceBusinessDataReport, "6");
    }

    /**
     * 事务所鉴证业务数据保存草稿
     *
     * @param assuranceBusinessDataReport
     * @return
     */
    @Log(title = "鉴证业务数据保存草稿", businessType = BusinessType.INSERT)
    @PostMapping("/saveDraft")
    @PreAuthorize("@ss.hasPermi('assurance:drafts')")
    public AjaxResult saveDraft(@RequestBody AssuranceBusinessDataReport assuranceBusinessDataReport) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = user.getIsOfficeAccount();
        if (1 == isOfficeAccount) {
            AntiCounterfeitingRegisteredOffice offices = iAssuranceBusinessDataReportService.getOfficeByNum();
            if (offices != null) {
                assuranceBusinessDataReport.setDataUploadPath(DataInPathConstants.OFFICE_INPUT);
                return AjaxResult.success(iAssuranceBusinessDataReportService.saveDraft(assuranceBusinessDataReport));
            } else {
                return AjaxResult.error("该事务所账号错误");
            }
        } else {
            return AjaxResult.success(iAssuranceBusinessDataReportService.saveDraft(assuranceBusinessDataReport));
        }

    }

    /**
     * 事务所业务数据导入
     *
     * @param file
     * @return
     */
    @Log(title = "事务所业务数据导入", businessType = BusinessType.IMPORT)
    @PostMapping("/officeImport")
    public AjaxResult officeImport(@RequestParam("file") MultipartFile file) throws Exception {
        if (checkAccount()) {
            return AjaxResult.error("不能使用非事务所账号导入!");
        }
        ExcelUtil<AssuranceBusinessDataReport> excelUtil = new ExcelUtil<>(AssuranceBusinessDataReport.class);
        List<AssuranceBusinessDataReport> list = excelUtil.importExcel(file.getInputStream());
        return AjaxResult.success(iAssuranceBusinessDataReportService.officeImport(list));
    }

    /**
     * 事务所业务数据导入
     *
     * @param file
     * @return
     */
    @Log(title = "事务所业务数据批量修改", businessType = BusinessType.IMPORT)
    @PostMapping("/officeImportUpdate")
    public AjaxResult officeImportUpdate(@RequestParam("file") MultipartFile file) throws Exception {
        if (checkAccount()) {
            return AjaxResult.error("不能使用非事务所账号导入!");
        }
        ExcelUtil<AssuranceBusinessDataReport> excelUtil = new ExcelUtil<>(AssuranceBusinessDataReport.class);
        List<AssuranceBusinessDataReport> list = excelUtil.importExcel(file.getInputStream());
        return AjaxResult.success(iAssuranceBusinessDataReportService.officeImportUpdate(list));
    }


    /**
     * 预上传录入
     *
     * @param report
     * @return/
     */
    @Log(title = "预上传录入", businessType = BusinessType.INSERT)
    @PostMapping("/preUploadSave")
    @PreAuthorize("@ss.hasPermi('assurance:list:preadd')")
    public AjaxResult preUploadSave(@RequestBody AssuranceBusinessDataReport report) {
        report.setDataUploadPath(DataInPathConstants.OFFICE_INPUT);
        report.setContrastStatus("0");
        return iAssuranceBusinessDataReportService.preUploadSave(report);
    }


    /**
     * 预上传事务所业务数据导入
     *
     * @return
     */
    @Log(title = "预上传事务所业务数据导入", businessType = BusinessType.IMPORT)
    @PostMapping("/preUploadImport")
    @PreAuthorize("@ss.hasPermi('assurance:list:preadd')")
    public AjaxResult preUploadImport(@RequestParam("file") MultipartFile file) throws Exception {
        if (checkAccount()) {
            return AjaxResult.error("不能使用非事务所账号导入!");
        }
        ExcelUtil<AssuranceBusinessDataReport> excelUtil = new ExcelUtil<>(AssuranceBusinessDataReport.class);
        List<AssuranceBusinessDataReport> list = excelUtil.importExcel(file.getInputStream());
        return AjaxResult.success(iAssuranceBusinessDataReportService.preUploadImport(list));
    }

    /**
     * 事务所业务数据预上传补录
     *
     * @param file
     * @return
     */
    @Log(title = "事务所业务数据预上传补录", businessType = BusinessType.IMPORT)
    @PostMapping("/preUploadImportSupplement")
    public AjaxResult preUploadImportSupplement(@RequestParam("file") MultipartFile file) throws Exception {
        if (checkAccount()) {
            return AjaxResult.error("不能使用非事务所账号补录!");
        }
        ExcelUtil<AssuranceBusinessDataReport> excelUtil = new ExcelUtil<>(AssuranceBusinessDataReport.class);
        List<AssuranceBusinessDataReport> list = excelUtil.importExcel(file.getInputStream());
        return AjaxResult.success(iAssuranceBusinessDataReportService.preUploadImportSupplement(list));
    }

    /**
     * 上注协录入数据
     *
     * @param report
     * @return
     */
    @Log(title = "上注协录入", businessType = BusinessType.INSERT)
    @PostMapping("/scipaSave")
    @PreAuthorize("@ss.hasPermi('assurance:scipa:power')")
    public AjaxResult scipaSave(@RequestBody AssuranceBusinessDataReport report) {
        report.setDataUploadPath(DataInPathConstants.SIA_INPUT);
        return iAssuranceBusinessDataReportService.scipaSave(report);
    }

    /**
     * 上注协去除重复防伪编码
     *
     * @param
     * @return
     */
   /* @Log(title = "上注协去除重复防伪编码", businessType = BusinessType.INSERT)
    @PostMapping("/makeAntiCode")
    public AjaxResult makeAntiCode() {
        iAssuranceBusinessDataReportService.makeAntiCode();
        return AjaxResult.success("success");
    }*/

    /**
     * wym
     * 上柱协导入鉴证业务数据（路径1导入）
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Log(title = "鉴证业务数据导入", businessType = BusinessType.IMPORT)
    @PostMapping("/siaImportReport")
    @PreAuthorize("@ss.hasPermi('assurance:scipa:power')")
    public AjaxResult siaImportReport(@RequestParam("file") MultipartFile file) throws Exception {
        Map<String, Object> res = new HashMap<>();
        ExcelUtil<AssuranceBusinessDataReport> util = new ExcelUtil<>(AssuranceBusinessDataReport.class);
        List<AssuranceBusinessDataReport> assuranceBusinessDataReports = util.importExcel(file.getInputStream(), 1);
        String taskNo = RandomStringUtils.randomAlphanumeric(12);
        res.put("taskNo", taskNo);
        iAssuranceBusinessDataReportService.siaImportReport(assuranceBusinessDataReports, taskNo, SecurityUtils.getLoginUser());
        return AjaxResult.success(res);
    }

    /**
     * wym
     * 传递任务编号，查询导入任务的实时进展
     *
     * @param taskNo
     * @return
     */
    @Log(title = "使用任务编号查询导入任务的实时进展", businessType = BusinessType.IMPORT)
    @GetMapping("/getImportProgressByTaskNo")
    @PreAuthorize("@ss.hasPermi('assurance:scipa:power')")
    public AjaxResult getImportProgressByTaskNo(String taskNo) {
        System.out.println("前端请求任务状态，触发了这个接口");
        Map<String, Object> progress = iAssuranceBusinessDataReportService.getImportProgressByTaskNo(taskNo);
        if (progress != null && progress.get("taskNo") != null) {
            return AjaxResult.success(progress);
        }
        return AjaxResult.error("任务编号不存在或已过期");
    }

    /**
     * 比对页面 保存
     * @param assuranceBusinessDataReport
     * @return
     */
    @Log(title = "对比修改鉴证业务报告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult compareEdit(@RequestBody AssuranceBusinessDataReport assuranceBusinessDataReport) {
        if (checkAccount()) {
            return AjaxResult.error("不能使用非事务所账号对比保存!");
        }
        return iAssuranceBusinessDataReportService.compareEdit(assuranceBusinessDataReport);
    }

    /**
     * 删除鉴证业务数据报告
     */
    @Log(title = "删除鉴证业务数据报告", businessType = BusinessType.DELETE)
    @ApiOperation("删除鉴证业务报告")
    @PostMapping("/remove")
    public AjaxResult remove(@RequestParam("businessIdS") String businessIdS) {
        return toAjax(iAssuranceBusinessDataReportService.deleteDeptByBusinessId(businessIdS));
    }

    /**
     * 根据鉴证业务数据报告id获取详细信息
     */
    @ApiOperation("查询鉴证业务报告")
    @GetMapping(value = "/{businessId}")
    @PreAuthorize("@ss.hasPermi('assurance:data:view')")
    public AjaxResult getInfo(@PathVariable Long businessId) {
        AssuranceBusinessDataReport assuranceBusinessDataReport = iAssuranceBusinessDataReportService.selectReportByBusinessId(businessId);
        if(assuranceBusinessDataReport  == null){
            return AjaxResult.error("没有查询到鉴证业务报告！");
        }
        if(assuranceBusinessDataReport != null && iAssuranceBusinessDataReportService.isOfficeData(assuranceBusinessDataReport)<1){
            return AjaxResult.success("无权限");
        }
        return  AjaxResult.success(assuranceBusinessDataReport);
    }

    /**
     * 鉴证业务修改历史数据导出
     *
     * @param businessId
     * @return
     */
    @Log(title = "鉴证业务修改历史数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/importEditHistory/{businessId}")
    public AjaxResult importEditHistory(@PathVariable Long businessId) {
        ExcelUtil<AssuranceBusinessDataReport> util = new ExcelUtil<>(AssuranceBusinessDataReport.class);
        List<AssuranceBusinessDataReport> list = iAssuranceBusinessDataReportService.importEditHistory(businessId);
        if (list == null || list.size() < 1) {
            return AjaxResult.success("没有该鉴证业务报告的修改历史数据!");
        }
        return util.exportExcel(list, "鉴证业务报告历史数据");
    }

    /**
     * 获取鉴证业务数据报告列表
     */
    @ApiOperation("获取鉴证业务报告列表")
    @GetMapping("/list")
    public TableDataInfo list(AssuranceBusinessDataReport assuranceBusinessDataReport) throws UnsupportedEncodingException {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = user.getIsOfficeAccount();
        List<AssuranceBusinessDataReport> list;
        if (assuranceBusinessDataReport.getReportNo() != null) {
            String decode = URLDecoder.decode(assuranceBusinessDataReport.getReportNo(), "UTF-8");
            assuranceBusinessDataReport.setReportNo(null);
            assuranceBusinessDataReport.setReportNoClean(StringUtils.removeSign(decode));
        }
        if (1 == isOfficeAccount) {
            AntiCounterfeitingRegisteredOffice office = iAssuranceBusinessDataReportService.getOfficeByNum();
            assuranceBusinessDataReport.setOfficeId(office.getOfficeId());
            TableDataInfo dataInfo = iAssuranceBusinessDataReportService.puSelect(assuranceBusinessDataReport);
            updateReportShowCode(dataInfo);
            return dataInfo;
        } else {
            if (iCheckUserPowerService.noAdminHashRole(RoleEnum.OFFICE_GROUPING_ADMIN.getRoleKey())) {
                List<String> officeIds = iAntiCounterfeitingRegisteredOfficeService.selectOfficeIdList();
                TableDataInfo dataInfo = iAssuranceBusinessDataReportService.zeSelect(assuranceBusinessDataReport, officeIds);
                updateReportShowCode(dataInfo);
                return dataInfo;
            } else if (iCheckUserPowerService.noAdminHashRole(RoleEnum.CZYH.getRoleKey())) {
                TableDataInfo dataInfo  = iAssuranceBusinessDataReportService.scipaSelect(assuranceBusinessDataReport, true);
                updateReportShowCode(dataInfo);
                return dataInfo;
            } else {
                TableDataInfo dataInfo = iAssuranceBusinessDataReportService.scipaSelect(assuranceBusinessDataReport, false);
                updateReportShowCode(dataInfo);
                return dataInfo;
            }
        }
    }
    private void updateReportShowCode( TableDataInfo dataInfo){
        List<AssuranceBusinessDataReport> list = (List<AssuranceBusinessDataReport>) dataInfo.getRows();
        for(int i=0;i<list.size();i++){
            AssuranceBusinessDataReport report = list.get(i);
            boolean flag1 = "2".equals(report.getContrastStatus());
            boolean flag2 = report.getCustomerBusinessLicense()  == null;
            boolean flag3 =report.getCustomerBusinessLicense()  == "";
            if(flag1 && ( flag2|| flag3)){
                report.setAntiCounterfeitingCoding(null);
            }
        }
        dataInfo.setRows(list);

    }

    /**
     * 获取鉴证业务报告草稿列表
     */
    @ApiOperation("获取鉴证业务报告草稿列表")
    @GetMapping("/list/draft")
    @PreAuthorize("@ss.hasPermi('assurance:drafts')")
    public TableDataInfo listDraft(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        startPage();
        List<AssuranceBusinessDataReport> list = iAssuranceBusinessDataReportService.selectReportListDraft(assuranceBusinessDataReport);
        return getDataTable(list);
    }

    /**
     * 鉴证业务报告申请退回
     * 不可退回
     *  3.事务所导入，未必对的不可退回，(没有财政数据)
     *  4.事务所导入已退回状态
     *  5.业务员不可申请财政退回（无权限)
     *
     *
     */
    @Log(title = "鉴证业务报告申请财政退回", businessType = BusinessType.UPDATE)
    @ApiOperation("鉴证业务报告申请退回")
    @GetMapping("/return")
    @PreAuthorize("@ss.hasPermi('assurance:apply:return')")
    public AjaxResult back(@RequestParam("businessId") Long businessId, @RequestParam("reason") String reason) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = user.getIsOfficeAccount();
        AssuranceBusinessDataReport report = iAssuranceBusinessDataReportService.selectReportByBusinessId(businessId);
        if (report == null) {
            return AjaxResult.error("鉴证业务报告错误!");
        }
        String contrastStatus = report.getContrastStatus();
        if (1 == isOfficeAccount) {
            if (contrastStatus != null){
                if ( "0".equals(contrastStatus)) {
                    return AjaxResult.error("该条数据财政系统还未导入!");
                }else{
                    if (!("0".equals(report.getApplyForFinancialRefund())) ) {
                        return AjaxResult.error("该条数据已申请财政退回!");
                    }
                }
            }else{
                return AjaxResult.error("鉴证业务报告错误!");
            }
        }else{
            return AjaxResult.error("不可申请财政退回!");
        }
        return toAjax(iAssuranceBusinessDataReportService.back(businessId, reason));
    }

    /**
     * 退回通过/不通过 applyForFinancialRefund: 2：财政退回通过，-2：财政退回不通过
     */
    @Log(title = "鉴证业务报告申请退回(退回通过/不通过)", businessType = BusinessType.UPDATE)
    @ApiOperation("退回通过/不通过")
    @PutMapping("/passOrNoPass")
    @PreAuthorize("@ss.hasPermi('assurance:return:approve')")
    public AjaxResult backPassOrNoPass(@Validated @RequestBody AssuranceBusinessDataReport assuranceBusinessDataReport) {
        return iAssuranceBusinessDataReportService.backPassOrNoPass( assuranceBusinessDataReport);
    }

    /**
     * 鉴证业务报告预上传配置
     *
     * @param configJson
     * @return
     */
    @Log(title = "鉴证业务报告预上传配置", businessType = BusinessType.UPDATE)
    @PutMapping("/preUploadConfig")
    public AjaxResult preUploadConfig(@RequestBody String configJson) {
        iAssuranceBusinessDataReportService.preUploadConfig(configJson);
        return AjaxResult.success();
    }

    /**
     * 数据状态：0：不予报备，1：强审通过
     */
    @Log(title = "数据强审", businessType = BusinessType.UPDATE)
    @ApiOperation("不予报备/强审通过")
    @GetMapping("/approval")
    @PreAuthorize("@ss.hasPermi('assurance:strong:approve')")
    public AjaxResult noFilingOrCompulsoryApproval(@RequestParam("businessId") Long businessId, @RequestParam("dataStatus") int dataStatus, @RequestParam("strongReason") String strongReason) {
        return toAjax(iAssuranceBusinessDataReportService.noFilingOrCompulsoryApproval(businessId, dataStatus, strongReason));
    }

    /**
     * 获取审核不通过原因
     *
     * @param businessId
     * @return
     */
    @GetMapping("/getFailedReason")
    public AjaxResult getFailedReason(@RequestParam("businessId") Long businessId) {
        return AjaxResult.success(iAssuranceBusinessDataReportService.getFailedReason(businessId));
    }

    /**
     * 获取作废原因
     *
     * @param businessId
     * @return
     */
    @GetMapping("/getVoidReason")
    public AjaxResult getVoidReason(@RequestParam("businessId") Long businessId) {
        return AjaxResult.success(iAssuranceBusinessDataReportService.getVoidReason(businessId));
    }

    /**
     * 获取申请财政退回原因
     *
     * @param businessId
     * @return
     */
    @GetMapping("/getApplyReturnReason")
    public AjaxResult getApplyReturnReason(@RequestParam("businessId") Long businessId) {
        return AjaxResult.success(iAssuranceBusinessDataReportService.getApplyReturnReason(businessId));
    }

    /**
     * 获取申请财政退回不通过原因
     *
     * @param businessId
     * @return
     */
    @GetMapping("/getApplyReturnNoReason")
    public AjaxResult getApplyReturnNoReason(@RequestParam("businessId") Long businessId) {
        return AjaxResult.success(iAssuranceBusinessDataReportService.getApplyReturnNoReason(businessId));
    }

    /**
     * 检查事务所名称是否已存在
     *
     * @param firmName
     * @return
     */
    @GetMapping("/checkFirmName")
    public AjaxResult checkFirmName(@RequestParam("firmName") String firmName) {
        return AjaxResult.success(iAssuranceBusinessDataReportService.checkFirmName(firmName));
    }

    /**
     * 根据防伪编码获取鉴证业务数据报告
     */
    @ApiOperation("根据防伪编码获取鉴证业务数据报告")
    @GetMapping(value = "/antiCounterfeitingCoding")
    public AjaxResult getAssuranceBusinessDataReport(@RequestParam("antiCode") String antiCounterfeitingCoding) throws Exception{
        Map<String, Object> result = new HashMap<>();
        AssuranceBusinessDataReport assuranceBusinessDataReport = new AssuranceBusinessDataReport();
        List<AssuranceBusinessDataReport> list = iAssuranceBusinessDataReportService.getAssuranceBusinessDataReport(antiCounterfeitingCoding);
        if(list.size()==1){
            assuranceBusinessDataReport =  list.get(0);
            Integer isPreUpload = assuranceBusinessDataReport.getIsPreUpload();
            if (isPreUpload != null && isPreUpload == 1) {
                if (!checkPreUpload(assuranceBusinessDataReport)) {
                    result.put("code", 500);
                    result.put("msg", "该报告信息尚未报备完整!");
                    return AjaxResult.success(result);
                }
            }
            result.put("code", 200);
            AntiCounterfeitingRegisteredOffice office = iAntiCounterfeitingRegisteredOfficeService.selectById(assuranceBusinessDataReport.getOfficeId());

            SysUser user = new SysUser();
            user.setOfficeId(assuranceBusinessDataReport.getOfficeId());
            user.setIsOfficeAdmin(1);
            user.setIsOfficeAccount(1);
            List<SysUser> userList = userService.selectOfficeUserList(user);
            if(userList.size()>0){
                office.setOperator(userList.get(0).getNickName());
                office.setOperatorNumber(userList.get(0).getTelephone());
                office.setPhoneNumberOfOperator(userList.get(0).getPhonenumber());
            }
            result.put("data", assuranceBusinessDataReport);
            result.put("office", office);
            return AjaxResult.success(result);
        }else if(list.size() == 0){
            result.put("code", 500);
            result.put("msg", "防伪编码错误!");
            return AjaxResult.success(result);
        }else{
            result.put("code", 555);
            result.put("msg", "防伪编码错误,请输入报告文号查询!");
            return AjaxResult.success(result);
        }
    }

    /**
     * 根据防伪编码获取鉴证业务数据报告
     */
    @ApiOperation("根据防伪编码和报告文号获取鉴证业务数据报告")
    @GetMapping(value = "/antiCounterfeitingCodingByReportNo")
    public AjaxResult getAssuranceBusinessDataReportByReportNo(@RequestParam("reportNo") String reportNo,@RequestParam("antiCode") String antiCounterfeitingCoding) throws Exception{
        Map<String, Object> result = new HashMap<>();
        String decode = URLDecoder.decode(reportNo, "UTF-8");
        AssuranceBusinessDataReport assuranceBusinessDataReport = new AssuranceBusinessDataReport();
        List<AssuranceBusinessDataReport> list = iAssuranceBusinessDataReportService.selectReportListByReportNo(decode,antiCounterfeitingCoding);
        if(list.size()==1){
            assuranceBusinessDataReport =  list.get(0);
            Integer isPreUpload = assuranceBusinessDataReport.getIsPreUpload();
            if (isPreUpload != null && isPreUpload == 1) {
                if (!checkPreUpload(assuranceBusinessDataReport)) {
                    result.put("code", 500);
                    result.put("msg", "该报告信息尚未报备完整!");
                    return AjaxResult.success(result);
                }
            }
            result.put("code", 200);
            AntiCounterfeitingRegisteredOffice office = iAntiCounterfeitingRegisteredOfficeService.selectById(assuranceBusinessDataReport.getOfficeId());

            SysUser user = new SysUser();
            user.setOfficeId(assuranceBusinessDataReport.getOfficeId());
            user.setIsOfficeAdmin(1);
            user.setIsOfficeAccount(1);
            List<SysUser> userList = userService.selectOfficeUserList(user);
            if(userList.size()>0){
                office.setOperator(userList.get(0).getNickName());
                office.setOperatorNumber(userList.get(0).getTelephone());
                office.setPhoneNumberOfOperator(userList.get(0).getPhonenumber());
            }
            result.put("data", assuranceBusinessDataReport);
            result.put("office", office);
            return AjaxResult.success(result);
        }else if(list.size() == 0){
            result.put("code", 500);
            result.put("msg", "报告文号错误!无数据");
            return AjaxResult.success(result);
        }else{
            result.put("code", 555);
            result.put("msg", "报告文号查询错误,请确认后输入，重复数据!");
            return AjaxResult.success(result);
        }
    }

    /**
     * 作废业务数据
     *
     * @param ids
     * @return
     */
    @GetMapping(value = "/voidBusinessData")
    @PreAuthorize("@ss.hasPermi('assurance:data:void')")
    public AjaxResult voidBusinessData(@RequestParam("ids") String ids, @RequestParam("reason") String reason) {
        return iAssuranceBusinessDataReportService.voidBusinessData(ids, reason);
    }

    /**
     * 鉴证业务数据导出
     *
     * @param report
     * @return
     */
    @PostMapping(value = "/exportBusinessData")
    @PreAuthorize("@ss.hasPermi('assurance:list:export')")
    public AjaxResult exportBusinessData(AssuranceBusinessDataReport report) throws Exception{
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = user.getIsOfficeAccount();
        List<AssuranceBusinessDataReport> list;
        if (report.getReportNo() != null) {
            String decode = URLDecoder.decode(report.getReportNo(), "UTF-8");
            report.setReportNo(null);
            report.setReportNoClean(StringUtils.removeSign(decode));
        }
        if (1 == isOfficeAccount) {
            AntiCounterfeitingRegisteredOffice office = iAssuranceBusinessDataReportService.getOfficeByNum();
            if (office != null) {
                report.setOfficeId(office.getOfficeId());
                TableDataInfo dataInfo = iAssuranceBusinessDataReportService.puSelect(report);
                list = (List<AssuranceBusinessDataReport>)dataInfo.getRows();
            }else{
                list = new ArrayList<>();
            }
        } else {
            if (iCheckUserPowerService.noAdminHashRole(RoleEnum.OFFICE_GROUPING_ADMIN.getRoleKey())) {
                List<String> officeIds = iAntiCounterfeitingRegisteredOfficeService.selectOfficeIdList();
                TableDataInfo dataInfo =  iAssuranceBusinessDataReportService.zeSelect(report, officeIds);
                list = (List<AssuranceBusinessDataReport>)dataInfo.getRows();
            } else if (iCheckUserPowerService.hasRole(RoleEnum.CZYH.getRoleKey())) {
                TableDataInfo dataInfo = iAssuranceBusinessDataReportService.scipaSelect(report, true);
                list = (List<AssuranceBusinessDataReport>)dataInfo.getRows();
            } else {
                TableDataInfo dataInfo =iAssuranceBusinessDataReportService.scipaSelect(report, false);
                list = (List<AssuranceBusinessDataReport>)dataInfo.getRows();
            }
        }
        //List<AssuranceBusinessDataReport> list = iAssuranceBusinessDataReportService.selectApprovalReportCount(report);
        ExcelUtil<AssuranceBusinessDataReport> util = new ExcelUtil<>(AssuranceBusinessDataReport.class);
        return util.exportExcel(list, "业务数据导出");
    }

    /**
     * 申请财政退回业务数据导出
     *
     * @param report
     * @return
     */
    @GetMapping(value = "/exportBusinessRefundData")
    public AjaxResult exportBusinessRefundData(AssuranceBusinessDataReport report) throws Exception{
        if (report.getReportNo() != null) {
            String decode = URLDecoder.decode(report.getReportNo(), "UTF-8");
            report.setReportNo(null);
            report.setReportNoClean(StringUtils.removeSign(decode));
        }
        TableDataInfo dataInfo = iAssuranceBusinessDataReportService.scipaSelect(report, true);
        List<AssuranceBusinessDataReport> list  = (List<AssuranceBusinessDataReport>)dataInfo.getRows();
        ExcelUtil<AssuranceBusinessDataReport> util = new ExcelUtil<>(AssuranceBusinessDataReport.class);
        return util.exportExcel(list, "业务数据导出");
    }

    /**
     * 比对页面获取数据
     * 根据鉴证业务表id获取录入数据和导入数据
     *
     * @param businessId 鉴证业务表id
     * @return 鉴证业务表报告录入数据和导入数据
     * @author wph 20200917
     */
    /*  @PreAuthorize("@ss.hasPermi('assurance:compare')")*/
    @ApiOperation("根据鉴证业务表id获取录入数据和导入数据")
    @ApiImplicitParam(name = "businessId", dataType = "Long", required = true)
    @GetMapping(value = "/getTempAndBusinessData")
    public AjaxResult getTempAndBusinessData(Long businessId) {
        return iAssuranceBusinessDataReportService.getTempAndBusinessData(businessId);
    }

    /**
     * 账号是否事务所账号检测
     *
     * @return
     */
    private boolean checkAccount() {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Integer isOfficeAccount = sysUser.getIsOfficeAccount();
        return !isOfficeAccount.equals(1);
    }

    /**
     * 审核鉴证业务数据
     *
     * @param report 鉴证业务数据报告
     * @author wph 20200921
     */
    @PreAuthorize("@ss.hasPermi('office:examine:audit')")
    @Log(title = "审核鉴证业务数据", businessType = BusinessType.UPDATE)
    @ApiOperation("审核鉴证业务数据")
    @ApiImplicitParam(name = "report", value = "鉴证业务数据报告", dataType = "AssuranceBusinessDataReport")
    @PostMapping("/auditImportReport")
    public AjaxResult auditImportReport(@RequestBody AssuranceBusinessDataReport report) {
        return AjaxResult.success(iAssuranceBusinessDataReportService.auditImportReport(report));
    }

    /**
     * 获取鉴证业务报告修改历史
     *
     * @param businessId
     * @return
     */
    @GetMapping("/getEditHistoryByBusinessId")
    public AjaxResult getEditHistoryByBusinessId(@RequestParam("businessId") Long businessId) {
        return AjaxResult.success(iAssuranceBusinessDataReportService.getEditHistoryByBusinessId(businessId));
    }



    /**
     * 检验预上传信息是否完备
     *
     * @param assuranceBusinessDataReport
     * @return
     */
    private Boolean checkPreUpload(AssuranceBusinessDataReport assuranceBusinessDataReport) {
        return StringUtils.isNotEmpty(assuranceBusinessDataReport.getReportTime()) && StringUtils.isNotEmpty(assuranceBusinessDataReport.getOpinionType());
    }

    /**
     * 获取待办事项  总数据（财政退回业务数据，需审核事务所业务数据，外省注册事务所审核数据，事务所联系人申请修改数据）
     */
    @ApiOperation("获取待办事项")
    @GetMapping("/approvalCount")
/*    @PreAuthorize("@ss.hasPermi('assurance:report:approval')")*/
    public AjaxResult getApproveCount() {
        return AjaxResult.success(iAssuranceBusinessDataReportService.getApproveCount());
    }

    /**
     * 根据报告id集合，获取报告封面图片base64字符串集合
     * @return
     */
    @ApiOperation("根据报告id集合，获取报告封面图片base64字符串集合")
    @GetMapping("/getCoverImgList")
    public AjaxResult getCoverImgList(String[] ids) {
        if(ids == null && ids.length == 0){
            return AjaxResult.error("必须传递报告id");
        }
        return AjaxResult.success(iAssuranceBusinessDataReportService.getReportImgsByIds(ids));
    }

    @ApiOperation("根据报告id集合，下载报告pdf的zip压缩包")
    @GetMapping("/getCoverZip")
    public void getCoverZip(String ids, HttpServletResponse response) throws Exception {
        byte[] decode = Base64.getDecoder().decode(ids);
        ids = new String(decode);
        String[] idArr = ids.split(",");
        Map<String, byte[]> reportZipByIds = iAssuranceBusinessDataReportService.getReportZipByIds(idArr);
        // 配置文件下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        //压缩包文件名
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
        // 下载文件时候防止显示中文乱码 指定文件类型 .zip
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("报告封面压缩包" + format.format(new Date())+".zip", "UTF-8"));
        //将文件打包成压缩文件
        ZipOutputStream zipout = new ZipOutputStream(response.getOutputStream());
        Set<Map.Entry<String, byte[]>> dataEntrys = reportZipByIds.entrySet();
        for (Map.Entry<String, byte[]> data : dataEntrys) {
            InputStream bufferIn = new BufferedInputStream( new ByteArrayInputStream( data.getValue()) );
            byte[] bs = new byte[1024];
            Arrays.fill(bs, (byte) 0);
            //创建压缩文件内的文件
            zipout.putNextEntry(new ZipEntry(data.getKey()));
            int len = -1;
            while ((len = bufferIn.read(bs)) > 0) {
                zipout.write(bs, 0, len);
            }
            bufferIn.close();
        }
        try {
            zipout.close();
        } catch (IOException e) {
        }


    }


}
